package com.bdqn.jwt1.util;

import io.jsonwebtoken.Claims;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.authentication.AuthenticationServiceException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.naming.AuthenticationException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.List;

public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {
    private final Logger logger = LoggerFactory.getLogger(getClass());

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        String token = request.getHeader("Authorization");
        if (token != null) {
             Claims claims = JwtUtil.parser(token);
            Date claimsExpiration = claims.getExpiration();
            Date now = new Date();
            if (now.getTime() > claimsExpiration.getTime()) {
                throw new AuthenticationServiceException("凭证已过期，请重新登录");
            }
            LinkedHashMap<String, Object> authenticationMap = (LinkedHashMap<String, Object>) claims.get("authentication");
            String username = (String) authenticationMap.get("name");
            ArrayList<LinkedHashMap<String, String>> authenticationList = (ArrayList<LinkedHashMap<String, String>>) authenticationMap.get("authorities");
            String[] authenticationStr = new String[authenticationList.size()];
            for (int i = 0; i < authenticationList.size(); i++) {
                authenticationStr[i] = authenticationList.get(i).get("authority");
            }
            List<GrantedAuthority> authorities = AuthorityUtils.createAuthorityList(authenticationStr);
            UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(username, null, authorities);
            SecurityContextHolder.getContext().setAuthentication(authentication);
        }
        filterChain.doFilter(request, response);
    }
}
